package com.jemmyee.task.web.controller.front;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.entity.User;
import com.jemmyee.core.utils.EncryptUtils;
import com.jemmyee.core.web.Constants;
import com.jemmyee.core.web.bean.ValidateCode;
import com.jemmyee.core.web.utils.MathUtils;
import com.jemmyee.task.web.TaskConstants;
import com.jemmyee.task.web.controller.kernel.BaseTaskFrontController;


/**
 * @Description:task前台Controller
 * @author:jemmyee@gmail.com
 * @date:2011-8-4
 * @version:v1.0
 */
@Controller("taskIndexController")
@RequestMapping(Constants.MV_URI_APP_TASK) 
public class IndexController extends BaseTaskFrontController{
	
	private static Log log= LogFactory.getLog(IndexController.class);
	/*分页查出保存的条件*/
	private static final String ENTITY_SESSION_BEAN="admin_session_bean_"+MathUtils.getRandomDouble();
	private static final String ROOT_VIEW=Constants.MV_URI_MAIN_FRONT+Constants.SYM_PATH_SEPARATOR+TaskConstants.ENTITY_TASK;
	
	/**
	* @Description:默认首页
	* @author:jemmyee@gmail.com
	* @date:2011-8-4
	*/
	@RequestMapping(Constants.MV_URI_COMM_INDEX)
	public ModelAndView index(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject("links", linkService.findAll());
		mv.setViewName(ROOT_VIEW+Constants.MV_URI_COMM_INDEX); 
		return mv;
	}
	/**
	 * @Description:登录页面
	 * @author:jemmyee@gmail.com
	 * @date:2011-8-4
	 */
	@RequestMapping("/toLogin")
	public ModelAndView toLogin(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName(ROOT_VIEW+"/login"); 
		return mv;
	}
	/**
	 * @Description:注册页面 
	 * @author:jemmyee@gmail.com
	 * @date:2011-8-4
	 */
	@RequestMapping("/toRegister")
	public ModelAndView toRegister(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName(ROOT_VIEW+"/register"); 
		return mv;
	}

	@RequestMapping("/header")
	public ModelAndView member(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName(ROOT_VIEW+"/header"); 
		return mv;
	}
	@RequestMapping("/footer")
	public ModelAndView footer(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName(ROOT_VIEW+"/footer"); 
		return mv;
	}
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(@RequestBody User bean,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			//判断验证码是否正确
			String validateCode=request.getSession().getAttribute(TaskConstants.SESSION_TASK_LOGIN_VALIDATE_CODE).toString();
			if(!bean.getVcode().equalsIgnoreCase(validateCode))
			{
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_LOGIN_VCODE);
				return model;
			}
			List<User> users=userService.findByProperty("name",bean.getName());
			if(users!=null&&users.size()<1)//账户不存在
			{
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_LOGIN_ERROR);
				return model;
			}else
			{
				User temp=users.get(0);
				if(temp.getPassword().equals(EncryptUtils.getMD5String(bean.getPassword())))//验证通过
				{
					request.getSession().setAttribute(Constants.ONLINE_USER,temp);
					temp.setLastLoginTime(new Date());
					userService.save(temp);
					model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
					return model;
				}
				else//验证不通过,密码不正确
				{
					model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_LOGIN_ERROR);
					return model;
				}
			}
				
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}
		return model;
	}
	
	/**
	* @Description:用户注册
	* @author:jemmyee@gmail.com
	* @date:2011-8-30
	*/
	@RequestMapping("/register")
	@ResponseBody
	public Map<String, Object> register(@RequestBody User bean,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			User temp = null;
			if (userService.findByProperty("name", bean.getName()) != null
					&& userService.findByProperty("name", bean.getName())
							.size() > 0) {
				temp = userService.findByProperty("name", bean.getName())
						.get(0);
			}
			if (temp != null && temp.getName().equals(bean.getName().trim())) {
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_RENAME);
			} else {
				bean.setName(bean.getName().trim());
				bean.setPassword(EncryptUtils.getMD5String(bean.getPassword()));
				bean.setAddTime(new Date());
				bean.setIsDelete((short)0);
				bean.setIsValidated((short)0);
				userService.save(bean);
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
			}
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}
		return model;
	}

	/**
	* @Description:登录验证码
	* @author:jemmyee@gmail.com
	* @date:2011-8-30
	*/
	@RequestMapping("/validateCode")
	public String validateCode(HttpServletRequest request,HttpServletResponse response){
		    ValidateCode code = new ValidateCode();
	        // 禁止图像缓存
	        response.setHeader("Pragma", "no-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);
	        response.setContentType("image/jpeg");
	        HttpSession session = request.getSession();

	        // 定义图像buffer
	        BufferedImage buffImg = new BufferedImage(code.getWidth(), code
	                .getHeight(), BufferedImage.TYPE_INT_RGB);
	        Graphics2D g = buffImg.createGraphics();

	        // 创建一个随机数生成器类
	        Random random = new Random();

	        // 将图像填充为白色
	        g.setColor(Color.WHITE);
	        g.fillRect(0, 0, code.getWidth(), code.getHeight() + 50);

	        // 创建字体，字体的大小应该根据图片的高度来定。
	        Font font = new Font("Fixedsys", Font.BOLD, code.getFontHeight());
	        // 设置字体
	        g.setFont(font);

	        // 画边框。
	        g.setColor(Color.BLACK);
	        g.drawRect(0, 0, 0, 0);

	        // 随机产生20条干扰线，使图象中的认证码不易被其它程序探测到。
	        g.setColor(Color.BLACK);
	        for (int i = 0; i < 20; i++) {
	            int x = random.nextInt(code.getWidth());
	            int y = random.nextInt(code.getHeight());
	            int xl = random.nextInt(1);
	            int yl = random.nextInt(1);
	            g.drawLine(x, y, x + xl, y + yl);
	        }

	        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
	        StringBuffer randomCode = new StringBuffer();
	        int red = 0, green = 0, blue = 0;

	        // 随机产生codeCount数字的验证码。
	        for (int i = 0; i < code.getCodeCount(); i++) {
	            // 得到随机产生的验证码数字。
	            String strRand = String.valueOf(ValidateCode.codeSequence[random
	                    .nextInt(ValidateCode.codeSequence.length)]);
	            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
	            red = random.nextInt(200);
	            green = random.nextInt(200);
	            blue = random.nextInt(200);

	            // 用随机产生的颜色将验证码绘制到图像中。
	            g.setColor(new Color(red, green, blue));
	            int point = 0;
	            if (i == 0)
	                point = 2;
	            else if (i == 1)
	                point = 18;
	            else if (i == 2)
	                point = 34;
	            else
	                point = 50;
	            g.drawString(strRand, point, code.getCodeY());

	            // 将产生的四个随机数组合在一起。
	            randomCode.append(strRand);
	        }
	        // 将四位数字的验证码保存到Session中。
	        session.setAttribute(TaskConstants.SESSION_TASK_LOGIN_VALIDATE_CODE, randomCode.toString());

	        // 将图像输出到Servlet输出流中。
	        g.dispose();
	        ServletOutputStream sos;
			try {
				sos = response.getOutputStream();
				ImageIO.write(buffImg, "jpeg", sos);
			        sos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        return null;
	}
	
}
